//
//  XYHomePictureView.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 16/1/2.
//  Copyright © 2016年 cn.weibo. All rights reserved.
//

import UIKit
import SDWebImage
private let XYHomePictureCellID = "XYHomePictureCellID"
private let ItemMargin: CGFloat = 5
private let ItemMaxCol = 3
private let ItemH: CGFloat = (kSCREENWITH - 2 * XYStatusCellMargin - 2 * ItemMargin) / CGFloat(ItemMaxCol)

class XYHomePictureView: UICollectionView,UICollectionViewDelegate,UICollectionViewDataSource {
    
    var viewModel: XYStatusViewModel?
    var pictures: [XYHomePicture]? {
        didSet {
            let count = pictures?.count ?? 0
            // 根据图片数量改变约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(getViewSize(count))
            }
            reloadData()
        }
    }
    private func getViewSize(count: Int) -> CGSize{
        // 通过count 计算item的大小
        if count == 1 {
            // 返回那一图片的大小
            // 从缓存里面取出图片 --> key 就是图片地址
            let key = pictures!.first!.thumbnail_pic
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            // 判断从缓存里面在否真的能够取出图片
            if image != nil {
                var size = image.size
                
                // 过窄的处理
                if size.width < 80 {
                    
                    let width: CGFloat = 80
                    let height = width / size.width * size.height
                    
                    size.width = width
                    // 约束最大的高度
                    size.height = height > 150 ? 150 : height
                }else if size.width > 200 {
                    // 图片过宽的处理
                    let width: CGFloat = 200
                    let height = width / size.width * size.height
                    
                    size.width = width
                    size.height = height
                }
                
                // 更改 cell 的大小
                let layout = collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = size
                
                return size
            }else {
                // 如果没有取出来，直接返回正方形的 size
                return CGSize(width: ItemH, height: ItemH)
            }
        }else{
            let layout = collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = CGSizeMake(ItemH, ItemH)
            
        }
        // 计算自身的大小
        // 计算列数
        var col = count > ItemMaxCol ? ItemMaxCol : count
        if count == 4{
            col = 2
        }
        let row = (count + ItemMaxCol - 1) / ItemMaxCol
        let width = CGFloat(col) * ItemH + CGFloat(col - 1) * ItemMargin
        let height = CGFloat(row) * ItemH + CGFloat(row - 1) * ItemMargin
        
        return CGSizeMake(width, height)
    }
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        backgroundColor = superview?.backgroundColor
        delegate = self
        dataSource = self
        registerClass(XYHomePictureViewCell.self, forCellWithReuseIdentifier: XYHomePictureCellID)
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(ItemH, ItemH)
        layout.minimumLineSpacing = ItemMargin
        layout.minimumInteritemSpacing = ItemMargin
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
extension XYHomePictureView {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XYHomePictureCellID, forIndexPath: indexPath) as! XYHomePictureViewCell
        let pictureInfo = pictures![indexPath.row]
        cell.pictureInfo = pictureInfo
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 明确问题：传递什么数据？当前 URL 的数组／当前用户选中的索引
        // 如何传递：通知
        // 通知：名字(通知中心监听)/object：发送通知的同时传递对象(单值)/ userInfo 传递多值的时候，使用的数据字典 -> Key
        let userInfo = [WBStatusSelectedPhotoIndexPathKey: indexPath,
            WBStatusSelectedPhotoURLsKey:viewModel!.thumbnailUrls!]
        
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusSelectedPhotoNotification,
            object: self,
            userInfo: userInfo)
    }
}
// MARK: - 照片查看器的展现协议
extension XYHomePictureView: PhotoBrowserPresentDelegate {
    
    /// 创建一个 imageView 在参与动画
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        
        let iv = UIImageView()
        
        // 1. 设置内容填充模式
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        // 2. 设置图像（缩略图的缓存）- SDWebImage 如果已经存在本地缓存，不会发起网络请求
        if let url = viewModel?.thumbnailUrls?[indexPath.item] {
            iv.sd_setImageWithURL(url)
        }
        
        return iv
    }
    
    /// 动画起始位置
    func photoBrowserPresentFromRect(indexPath: NSIndexPath) -> CGRect {
        
        // 1. 根据 indexPath 获得当前用户选择的 cell
        let cell = self.cellForItemAtIndexPath(indexPath)!
        
        // 2. 通过 cell 知道 cell 对应在屏幕上的准确位置
        // 在不同视图之间的 `坐标系的转换` self. 是 cell 都父视图
        // 由 collectionView 将 cell 的 frame 位置转换的 keyWindow 对应的 frame 位置
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        // 测试转换 rect 的位置
        //        let v = UIView(frame: rect)
        //        v.backgroundColor = UIColor.redColor()
        // 再次测试
        //        let v = imageViewForPresent(indexPath)
        //        v.frame = rect
        //
        //        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
        return rect
    }
    
    /// 目标位置
    func photoBrowserPresentToRect(indexPath: NSIndexPath) -> CGRect {
        
        // 根据缩略图的大小，等比例计算目标位置
        guard let key = viewModel?.thumbnailUrls?[indexPath.item].absoluteString else {
            return CGRectZero
        }
        // 从 sdwebImage 获取本地缓存图片
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
            return CGRectZero
        }
        
        // 根据图像大小，计算全屏的大小
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        
        // 对高度进行额外处理
        let screenHeight = UIScreen.mainScreen().bounds.height
        var y: CGFloat = 0
        if h < screenHeight {       // 图片短，垂直居中显示
            y = (screenHeight - h) * 0.5
        }
        
        let rect = CGRect(x: 0, y: y, width: w, height: h)
        
        // 测试位置
        //        let v = imageViewForPresent(indexPath)
        //        v.frame = rect
        //
        //        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
        return rect
    }
}

// MARK: 自定义cell
class XYHomePictureViewCell: UICollectionViewCell {
    
    var pictureInfo: XYHomePicture? {
        
        didSet {
            if let urlString = pictureInfo?.thumbnail_pic {
                gifIcon.hidden = !urlString.hasSuffix(".gif")
                if let url = NSURL(string: urlString){
                    imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "timeline_image_placeholder"))
                }
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(imageView)
        contentView.addSubview(gifIcon)
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        gifIcon.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(contentView)
            make.bottom.equalTo(contentView)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 懒加载控件
    private lazy var imageView: UIImageView = {
        
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    /// git图标
    private lazy var gifIcon: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
}
